#include <StdAfx.h>
#include "VItemDelegate.h"

// VEnumEditor ////////////////////////////////////////////////////////////////

//
VEnumEditor::VEnumEditor(const QMetaProperty &propEnum,QWidget *parent)
	:QComboBox(parent)
{
	QStringList list = VPropertyEnum(propEnum).displayList();
	for (int i = 0; i < list.count(); ++i)
		addItem(list[i]);
}

// VItemDelegate //////////////////////////////////////////////////////////////

//
QWidget *VItemDelegate::createEditor
(
	QWidget *parent,
	const QStyleOptionViewItem &option,
	const QModelIndex &index
) 
const
{
	QVariant data = index.model()->data(index, Qt::EditRole);
	VTreeNode *node = nodeFromIndex(index);
	QMetaProperty mp = VProperty(node->item()).metaProperty(index.column());
	QWidget *widget = NULL;

	if (mp.isEnumType())
		widget = new VEnumEditor(mp,parent);
	else
		widget = QStyledItemDelegate::createEditor(parent,option,index);
		
	widget->setFont(VItemStyle::style(node->item(),index.column()).font);
	return widget;
}

//
void VItemDelegate::setEditorData
(
	QWidget *editor_,
	const QModelIndex &index
) 
const
{
	QVariant data = index.model()->data(index, Qt::EditRole);
	VTreeNode *node = nodeFromIndex(index);
	QMetaProperty mp = VProperty(node->item()).metaProperty(index.column());

	if (mp.isEnumType())
	{
		VEnumEditor *editor = qobject_cast<VEnumEditor*>(editor_);
		editor->setValue(data);
	}
	else
		QStyledItemDelegate::setEditorData(editor_,index);
}

//
void VItemDelegate::setModelData
(
	QWidget *editor_,
	QAbstractItemModel *model,
	const QModelIndex &index
) 
const
{
	QVariant data = model->data(index, Qt::EditRole);
	VTreeNode *node = nodeFromIndex(index);
	QMetaProperty mp = VProperty(node->item()).metaProperty(index.column());

	if (mp.isEnumType())
	{
		VEnumEditor *editor = qobject_cast<VEnumEditor*>(editor_);
		model->setData(index,editor->value(),Qt::EditRole);
	}
	else
		QStyledItemDelegate::setModelData(editor_,model,index);
}

//
VTreeNode *VItemDelegate::nodeFromIndex(const QModelIndex &index) const
{
	const QAbstractItemModel *am = index.model();
	QAbstractProxyModel *pm = qobject_cast<QAbstractProxyModel*>((QAbstractItemModel*)am);
	QModelIndex sIndex = index;

	if (pm)
		sIndex = pm->mapToSource(index);

	return static_cast<VTreeNode*>(sIndex.internalPointer());
}
